import * as FileSystem from "expo-file-system";
import * as ImagePicker from "expo-image-picker";

import {
  Alert,
  Button,
  Image,
  Modal,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import React, { useEffect, useState } from "react";

// 假设你有一个占位符图像
const PlaceholderImage = require("./../../assets/images/splash.png");
const ImageViewer = ({ selectedImage }) => {
  const imageSource = selectedImage ? { uri: selectedImage } : PlaceholderImage;
  return <Image source={imageSource} style={styles.image} />;
};

export default function App() {
  const [selectedImage, setSelectedImage] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [tempImageUri, setTempImageUri] = useState(null);

  const placeholderImageUri = FileSystem.documentDirectory + "placeholder.png";

  useEffect(() => {
    const loadWallpaper = async () => {
      const fileName = `${FileSystem.documentDirectory}selected_image.jpg`;
      const fileInfo = await FileSystem.getInfoAsync(fileName);
      if (fileInfo.exists) {
        setSelectedImage(fileName);
      } else {
        setSelectedImage(placeholderImageUri);
      }
    };
    loadWallpaper();
  }, []);

  const pickImageAsync = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      quality: 1,
    });

    if (!result.canceled) {
      setTempImageUri(result.assets[0]?.uri);
    } else {
      Alert.alert("You did not select any image.");
    }
  };

  const handleConfirm = async () => {
    const imageUri = tempImageUri;
    const fileName = `${
      FileSystem.documentDirectory
    }selected_image_${Date.now()}.jpg`;

    try {
      const fileInfo = await FileSystem.getInfoAsync(imageUri);
      if (!fileInfo.exists) {
        Alert.alert("Error: File does not exist");
        return;
      }

      await FileSystem.copyAsync({
        from: imageUri,
        to: fileName,
      });

      await FileSystem.copyAsync({
        from: imageUri,
        to: placeholderImageUri,
      });

      setSelectedImage(fileName);
      setModalVisible(false);
      Alert.alert("Image saved successfully!");
    } catch (error) {
      Alert.alert("Error saving image: " + error.message);
    }
  };

  const handleCancel = () => {
    setTempImageUri(null);
    setModalVisible(false);
  };

  return (
    <View style={styles.container}>
      <View style={styles.imageContainer}>
        <ImageViewer selectedImage={selectedImage} />
      </View>
      <Button
        title="Pick and Save Image"
        onPress={() => {
          setModalVisible(true);
          pickImageAsync();
        }}
      />

      <Modal
        visible={modalVisible}
        animationType="slide"
        onRequestClose={() => setModalVisible(false)}
      >
        <View style={styles.modalContainer}>
          {tempImageUri && (
            <Image source={{ uri: tempImageUri }} style={styles.imagePreview} />
          )}
          <View style={styles.buttonContainer}>
            <TouchableOpacity style={styles.button} onPress={handleConfirm}>
              <Text style={styles.buttonText}>Confirm</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.button} onPress={handleCancel}>
              <Text style={styles.buttonText}>Cancel</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#fff",
  },
  imageContainer: {
    width: "100%",
    height: "80%",
    justifyContent: "center",
    alignItems: "center",
  },
  image: {
    width: "100%",
    height: "100%",
    resizeMode: "cover",
  },
  modalContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "white",
  },
  imagePreview: {
    width: 300,
    height: 300,
    resizeMode: "cover",
    marginBottom: 20,
  },
  buttonContainer: {
    flexDirection: "row",
    justifyContent: "space-around",
    width: "80%",
  },
  button: {
    padding: 10,
    backgroundColor: "#007BFF",
    borderRadius: 5,
  },
  buttonText: {
    color: "white",
  },
});
